package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminUerMapper;
import com.heima.admin.service.AdminUerService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
@Transactional
@Slf4j
public class AdminUerServiceImpl extends ServiceImpl<AdminUerMapper, AdUser> implements AdminUerService {

    /**
     * 管理员登录
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //校验参数
        if(StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或者密码不能为空");
        }
        //查询用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if(adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //比对密码 ,MD5加密,盐
        String salt = adUser.getSalt();
        String dbPassword = adUser.getPassword();
        String password = adUserDto.getPassword();
        password = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if(!password.equals(dbPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //返回数据,jwt
        AdUserVo adUserVo = new AdUserVo();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        adUser.setPassword("");
        adUser.setSalt("");
        adUser.setLoginTime(new Date());
        adUserVo.setUser(adUser);
        adUserVo.setToken(token);
        return ResponseResult.okResult(adUserVo);
    }
}
